import os
import requests
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()

# 读取 .env 文件中的配置
ORG_NAME = os.getenv("ORG_NAME")
USER_NAME = os.getenv("USER_NAME")
OPENAPI_ACCESS_TOKEN = os.getenv("OPENAPI_ACCESS_TOKEN")

# 定义 Gitee API 端点
ORG_REPOS_URL = "https://gitee.com/api/v5/orgs/{org}/repos"
USER_REPOS_URL = "https://gitee.com/api/v5/users/{username}/repos"

# 请求头
headers = {
    'Content-Type': 'application/json;charset=UTF-8'
}

# 定义每页数量
PER_PAGE = 100

# 根据组织名获取仓库列表
def get_org_repos(org_name, access_token):
    url = ORG_REPOS_URL.format(org=org_name)
    params = {
        'access_token': access_token,
        'type': 'all',
        'page': 1,
        'per_page': PER_PAGE
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json()

# 根据用户名获取仓库列表
def get_user_repos(user_name, access_token):
    url = USER_REPOS_URL.format(username=user_name)
    params = {
        'access_token': access_token,
        'type': 'all',
        'sort': 'full_name',
        'page': 1,
        'per_page': PER_PAGE
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json()

# 将仓库的 html_url 写入 source.txt 文件
def write_repos_to_file(repos):
    with open('source.txt', 'a') as file:
        for repo in repos:
            file.write(f"{repo['html_url']}\n")
    print("[INFO] Successfully wrote repository URLs to source.txt")

def main():
    # 清空 source.txt 文件
    with open('source.txt', 'w') as file:
        pass

    if ORG_NAME and USER_NAME:
        print("[WARNING] Both ORG_NAME and USER_NAME are set. Only ORG_NAME will be processed. To process USER_NAME, please unset ORG_NAME.")

    if ORG_NAME:
        print(f"[INFO] Fetching repositories for organization: {ORG_NAME}")
        org_repos = get_org_repos(ORG_NAME, OPENAPI_ACCESS_TOKEN)
        write_repos_to_file(org_repos)
    elif USER_NAME:
        print(f"[INFO] Fetching repositories for user: {USER_NAME}")
        user_repos = get_user_repos(USER_NAME, OPENAPI_ACCESS_TOKEN)
        write_repos_to_file(user_repos)
    else:
        print("[ERROR] Neither ORG_NAME nor USER_NAME is set. Please set one.")

if __name__ == "__main__":
    main()
